package com.pig4cloud.pig.module.controller.mer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.core.util.RegexUtil;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.mer.MerCoupon;
import com.pig4cloud.pig.module.api.entity.mer.MerCouponProduct;
import com.pig4cloud.pig.module.api.entity.product.Product;
import com.pig4cloud.pig.module.api.entity.product.ProductType;
import com.pig4cloud.pig.module.service.mer.IMerCouponProductService;
import com.pig4cloud.pig.module.service.mer.IMerCouponService;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.product.IProductService;
import com.pig4cloud.pig.module.service.product.IProductTypeService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 商家抵扣券Controller
 *
 * @author ruoyi
 * @date 2022-02-24
 */
@Validated
@Api(value = "商家抵扣券控制器", tags = {"商家抵扣券管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/mer/coupon")
public class MerCouponController {

    private final IMerCouponService merCouponService;
    private final IMerService merService;
    private final IMerCouponProductService merCouponProductService;
    private final IProductService productService;
    private final IProductTypeService productTypeService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

    /**
     * 查询商家抵扣券列表
     */
    @ApiOperation("查询商家抵扣券列表")
    @PreAuthorize("@pms.hasPermission('module:mercoupon:list')")
    @GetMapping("/list")
    public TableDataInfo<MerCoupon> list(@Validated MerCoupon merCoupon) {
        QueryWrapper<MerCoupon> qw = new QueryWrapper<>();
        if(merCoupon.getMerId()!=null){
            qw.eq("mer_id", merCoupon.getMerId());
        }
        TableDataInfo<MerCoupon> td = PageUtils.buildDataInfo(merCouponService.page(PageUtils.buildPage(),qw));
        List<MerCoupon> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (MerCoupon merCoupon1 : list){
        		if(StrUtil.isNotEmpty(merCoupon1.getImgUrl())){
        			merCoupon1.setImgUrlPath(imgUrl + merCoupon1.getImgUrl());
				}
			}
		}
        return td;
    }

    /**
     * 获取商家抵扣券详细信息
     */
    @ApiOperation("获取商家抵扣券详细信息")
    @PreAuthorize("@pms.hasPermission('module:mercoupon:query')")
    @GetMapping("/{id}")
    public R<MerCoupon> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        MerCoupon merCoupon = merCouponService.getById(id);
        if(merCoupon!=null){
			if(StrUtil.isNotEmpty(merCoupon.getImgUrl())){
				merCoupon.setImgUrlPath(imgUrl + merCoupon.getImgUrl());
			}
            List<Product> products = new ArrayList<>();
            QueryWrapper<MerCouponProduct> qw = new QueryWrapper<>();
            qw.eq("coupon_id",merCoupon.getId());
            qw.eq("mer_id",merCoupon.getMerId());
            List<MerCouponProduct> list = merCouponProductService.list(qw);
            if(CollUtil.isNotEmpty(list)){
                for (MerCouponProduct couponProduct : list){
                    Product product1 = productService.findById(couponProduct.getProductId());
                    if(product1!=null){
                        if(StrUtil.isNotEmpty(product1.getImage())){
                            if(StrUtil.isNotEmpty(product1.getImage()) && product1.getImage().indexOf("http") < 0){
                                product1.setImagePath(imgUrl + product1.getImage());
                            }else{
                                product1.setImagePath(product1.getImage());
                            }
                        }else{
                            product1.setImagePath("");
                        }

                        ProductType productType = productTypeService.findById(product1.getCateChildId());
                        if(productType!=null){
                            product1.setCateChildName(productType.getTypeName());
                        }

                        if(StrUtil.isNotEmpty(product1.getQrCode())){
                            product1.setQrCode(imgUrl + product1.getQrCode());
                        }

                        List<String> sliderImageArray = new ArrayList<>();
                        product1.setSliderImageArray(sliderImageArray);
                        if(StrUtil.isNotEmpty(product1.getSliderImage())){
                            String[] sliderImages = product1.getSliderImage().split(",");
                            for (String img: sliderImages){
                                if(StrUtil.isNotEmpty(img) && img.indexOf("http") < 0){
                                    sliderImageArray.add(imgUrl + img);
                                }else{
                                    sliderImageArray.add(img);
                                }
                            }
                            product1.setSliderImageArray(sliderImageArray);
                        }
                    }
                    products.add(product1);
                }
            }
            merCoupon.setMerProducts(products);
        }
        return R.ok(merCoupon);
    }

    /**
     * 新增商家抵扣券
     */
    @ApiOperation("新增商家抵扣券")
    @PreAuthorize("@pms.hasPermission('module:mercoupon:add')")
    @SysLog("商家抵扣券")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody MerCoupon merCoupon) {
        Mer mer = merService.getById(merCoupon.getMerId());
        if(mer!=null){
            merCoupon.setMerName(mer.getShopName());
        }

        if(StrUtil.isNotEmpty(merCoupon.getBuyingTips())){
			String buyTips = EmojiParser.parseToAliases(merCoupon.getBuyingTips());
			merCoupon.setBuyingTips(RegexUtil.convertProductDescription(buyTips));
		}

		if(StrUtil.isNotEmpty(merCoupon.getRemark())){
			String remark = EmojiParser.parseToAliases(merCoupon.getRemark());
			merCoupon.setRemark(RegexUtil.convertProductDescription(remark));
		}

        int ret = merCouponService.save(merCoupon) ? 1 : 0;
        if(ret > 0){
            addCouponProduct(merCoupon);
        }
        return R.okByRow(ret);
    }

    private void addCouponProduct(MerCoupon merCoupon){

//         抵扣券
        if(merCoupon.getIsAll() == 0){
            QueryWrapper<MerCouponProduct> qw = new QueryWrapper<>();
            qw.eq("coupon_id",merCoupon.getId());
            List<MerCouponProduct> couponProducts = merCouponProductService.list(qw);
            if(CollUtil.isNotEmpty(couponProducts)){
                for (MerCouponProduct couponProduct : couponProducts){
                    if(!merCoupon.getMerProductIds().contains(couponProduct.getId())){
                        merCouponProductService.removeById(couponProduct.getId());
                    }
                }
            }

            List<Integer> productIds = merCoupon.getMerProductIds();
            for (Integer productId : productIds){
                QueryWrapper<MerCouponProduct> qw1 = new QueryWrapper<>();
                qw1.eq("coupon_id",merCoupon.getId());
                qw1.eq("product_id",productId);
                qw1.eq("mer_id",merCoupon.getMerId());
                qw1.last("limit 1");
                MerCouponProduct couponProduct = merCouponProductService.getOne(qw1);
                if(couponProduct == null){
                    couponProduct = new MerCouponProduct();
                    couponProduct.setMerId(merCoupon.getMerId());
                    couponProduct.setProductId(productId);
                    couponProduct.setCouponId(merCoupon.getId());
                    boolean bl = merCouponProductService.save(couponProduct);
                }
            }
        }
    }

    /**
     * 修改商家抵扣券
     */
    @ApiOperation("修改商家抵扣券")
    @PreAuthorize("@pms.hasPermission('module:mercoupon:edit')")
    @SysLog("商家抵扣券")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody MerCoupon merCoupon) {

		if(StrUtil.isNotEmpty(merCoupon.getBuyingTips())){
			String buyTips = EmojiParser.parseToAliases(merCoupon.getBuyingTips());
			merCoupon.setBuyingTips(RegexUtil.convertProductDescription(buyTips));
		}

		if(StrUtil.isNotEmpty(merCoupon.getRemark())){
			String remark = EmojiParser.parseToAliases(merCoupon.getRemark());
			merCoupon.setRemark(RegexUtil.convertProductDescription(remark));
		}

        int ret = merCouponService.updateById(merCoupon) ? 1 : 0;
        if(ret > 0){
            addCouponProduct(merCoupon);
        }
        return R.okByRow(ret);
    }

    /**
     * 删除商家抵扣券
     */
    @ApiOperation("删除商家抵扣券")
    @PreAuthorize("@pms.hasPermission('module:mercoupon:remove')")
    @SysLog("商家抵扣券")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(merCouponService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
